package com.tian.hello.srollview

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.tian.hello.R
import com.tian.hello.databinding.ActivityListviewBinding

class ListViewTestAc : AppCompatActivity() {

    private lateinit var binding: ActivityListviewBinding
    private lateinit var adapter: MAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityListviewBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 给listview设定数据
        val data = mutableListOf<String>()
        for (i in 0..22) {
            data.add(i.toString())
        }
        adapter = MAdapter(data)
        binding.testList.adapter = adapter
        adapter.notifyDataSetChanged()
    }

    class MAdapter(val data: List<String>) : BaseAdapter() {
        override fun getCount() = data.size

        override fun getItem(position: Int) = data[position]

        override fun getItemId(position: Int) = position.toLong()

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view: View
            val vh: VH
            if (convertView == null) {
                view = LayoutInflater.from(parent.context).inflate(R.layout.item_view, null) as ViewGroup
                vh = VH(view)
                view.tag = vh
            } else {
                view = convertView
                vh = convertView.tag as VH
            }

            vh.getViewById<TextView>(R.id.id_num).text = "$position ${data[position]} ${view}"

            Log.d("ListTest", parent.childCount.toString())
            return view
        }
    }

    class VH(val itemView: ViewGroup) {

        val views = SparseArray<View>()

        fun <T : View?> getViewById(viewId: Int): T {
            var target = views[viewId]
            if (target == null) {
                target = itemView.findViewById(viewId)
                views.put(viewId, target)
            }
            return target as T
        }
    }

}